<template>
    <view class="scanCode">
        <u-notify ref="uNotify"></u-notify>
        <u-modal :show="mshow" @confirm="mconfirm" title="提示" :content='mcontent'></u-modal>
        <u-loading-page class="loading" bg-color="rgba(0,0,0,0.5)" :loading="loading"></u-loading-page>
        <view class="scanCodetopimg">
            <image class="sandcode" src="../../static/imgs/sandcode.png" @click="scanCode()"></image>
            <image class="grandTotal" src="../../static/imgs/grandTotal.png" mode="aspectFit"
                v-if="userInfo?userInfo.roleName=='水工角色'&&recordForm.length:false"></image>
            <view class="vh-cb grandTotalText" v-if="userInfo?userInfo.roleName=='水工角色'&&recordForm.length:false">
                <view class="title">
                    累计获得奖励
                </view>
                <view class="num">
                    ￥{{leijishourudata?leijishourudata:0}}
                </view>
            </view>
        </view>
        <view class="recordBox" v-if="recordForm.length">
            <view class="recordtitle">
                扫描记录
            </view>
            <view class="recordItem" v-for="(machItem,machIndex) in recordForm" :key="machIndex">
                <view class="dpname">
                    {{machItem.machName?machItem.machName:''}}
                </view>
                <!-- <view class="warp"> -->
                <!-- <view class="box"> -->
                <t-table @change="change">
                    <t-tr class="tabtitle">
                        <t-th>序号</t-th>
                        <t-th>
                            <view style="width:calc(100vw - 300rpx)">
                                商品名称
                            </view>
                        </t-th>
                        <t-th>操作</t-th>
                    </t-tr>
                    <t-tr v-for="(item,index) in machItem.goods" :key="index">
                        <t-th><text style="font-weight:400">{{index+1}}</text></t-th>
                        <t-th class="content">
                            <view style="width:calc(100vw - 300rpx)">
                                <view class="vh-cs">
                                    <text class="numbering">编号{{item.number}}</text>
                                </view>
                                <view class="title">{{item.name}}</view>
                            </view>
                        </t-th>
                        <t-th>
                            <text class="deleteItem" @click="deleteItem(machIndex,index)">移除</text>
                        </t-th>
                    </t-tr>
                </t-table>
                <u--form :model="machItem" :ref="'uForm'+machIndex" :rules="rules" v-if="userInfo.roleName=='水工角色'">
                    <u-form-item label="施工地址" prop="address">
                        <u--input v-model="recordForm[machIndex].address" @input="changeinput($event,machIndex)" />
                    </u-form-item>
                    <u-form-item label="施工时间" prop="constructionTime" borderBottom @click="showTimePick = true; hideKeyboard(machIndex)" ref="item1">
                        <u--input v-model="machItem.constructionTime" disabled disabledColor="#ffffff" placeholder="请选择施工时间" border="none"></u--input>
                        <u-icon slot="right" name="arrow-right"></u-icon>
                    </u-form-item>
                    <u-form-item label="现场施工图" prop="images">
                        <view class="u-demo-block shigongimgs">
                            <!-- <text class="u-demo-block__title">隐藏上传按钮</text> -->
                            <view class="u-demo-block__content">
                                <view class="u-page__upload-item">
                                    <!-- :maxCount="2" -->
                                    <u-upload :fileList="machItem.fileList" @afterRead="(arg)=>afterRead(arg,machItem,machIndex)"
                                        @delete="(arg)=>deletePic(arg,machItem,machIndex)" name="4" multiple :maxCount="3">
                                    </u-upload>
                                </view>
                            </view>
                        </view>
                    </u-form-item>

                </u--form>
                <u--form :model="machItem" :ref="'uForm'+machIndex" :rules="rules" v-if="userInfo.roleName=='商家角色'">
                    <!-- <u-form-item label=""> -->
                    <u-radio-group placement="row" v-model="recordForm[machIndex].type">
                        <u-radio :customStyle="{marginBottom: '8px'}" label="退货" :value="2" :name="2">
                        </u-radio>
                        <u-radio :customStyle="{marginBottom: '8px'}" label="核销" :value="1" :name="1">
                        </u-radio>
                    </u-radio-group>

                    <!-- </u-form-item> -->

                </u--form>
                <u-datetime-picker :show="showTimePick" :value="birthday" mode="date" closeOnClickOverlay @confirm="birthdayConfirm"
                    @cancel="birthdayClose" @close="birthdayClose"></u-datetime-picker>
                <!-- </view> -->
                <!-- </view> -->
            </view>
            <u-button @click="submit"  :disabled="disabledbtn">提交</u-button>

        </view>
        <z-navigation style="position: absolute;"></z-navigation>

    </view>
</template>
<script>
export default {
    data() {
        return {
            userInfo: {},
            loading: false,
            showTimePick: false,
            birthday: Number(new Date()),
            recordForm: [],
            fileList4: [],
            nowMachIndex: '',
            rules: {
                address: [
                    {
                        required: true,
                        message: '请填写施工地址',
                        trigger: ['blur', 'change']
                    }
                ],
                constructionTime: [
                    {
                        required: true,
                        message: '请选择施工时间',
                    }
                ],
                images: [
                    {
                        required: true,
                        message: '请上传图片',
                    }
                ],
            },
            mshow: false,
            mcontent: '',
            leijishourudata:0,
            disabledbtn: false,
        }
    },
    //第一次加载
    onLoad(e) {
        // 隐藏原生的tabbar
        uni.hideTabBar();
    },
    //页面显示
    onShow() {
        // 隐藏原生的tabbar
        uni.hideTabBar();
        this.userInfo = this.$store.state.userInfo ? this.$store.state.userInfo : ''
        if (this.userInfo) {
            if (this.userInfo.roleName == '水工角色') {
                // if(this.userInfo.ro)
                this.leijishouru()
            }
        }
    },
    methods: {


        leijishouru() {
            this.$http.get('/app/leijishouru/').then(val => {
                this.leijishourudata = val.data
                console.log(this.leijishourudata)

            })
        },
        mconfirm() {
            this.mshow = false
        },
        //前端移除某件商品
        deleteItem(machIndex, index) {
            this.recordForm[machIndex].goods.splice(index, 1)
            if (this.recordForm[machIndex].goods.length == 0) {
                this.recordForm.splice(machIndex, 1)
            }
            console.log(this.recordForm[machIndex].goods)

        },
        changeinput(value, machIndex) {
            this.recordForm[machIndex].address = value
            this.$forceUpdate()
        },
        // 删除图片
        deletePic(event, machItem, machIndex) {
            this.recordForm[machIndex].fileList.splice(event.index, 1)
            this.recordForm[machIndex].images.splice(event.index, 1)
            console.log(this.recordForm)
        },
        // 新增图片
        async afterRead(event, machItem, machIndex) {
            console.log(machIndex)
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this.recordForm[machIndex].fileList.length
            lists.map((item) => {
                this.recordForm[machIndex].fileList.push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url, machItem, machIndex)
                let item = this.recordForm[machIndex].fileList[fileListLen]
                this.recordForm[machIndex].fileList.splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
                console.log(this.recordForm[machIndex].fileList)
            }
        },
        uploadFilePromise(url, machItem, machIndex) {
            let that = this
            //  this.actionUrl = process.env.VUE_APP_BASE_URL + "/file/upload";
            return new Promise((resolve, reject) => {
                console.log(url)
                let a = uni.uploadFile({
                    url: that.$base.baseUrl + "sys/common/upload", // 仅为示例，非真实的接口地址
                    filePath: url,
                    name: 'file',
                    header: {
                        "token": uni.getStorageSync("userInfo").token //token校验
                    },
                    success: (res) => {
                        that.recordForm[machIndex].images = that.recordForm[machIndex].images ? that.recordForm[machIndex].images : []
                        that.recordForm[machIndex].images.push(JSON.parse(res.data).data)
                        resolve(res.data.data)

                        // images
                        // setTimeout(() => {
                        // }, 1000)
                    }
                });
            })
        },
        //扫码
        scanCode() {
            let that = this
            if (this.userInfo.roleName != '水工角色' && this.userInfo.roleName != '商家角色') {
                this.mshow = true
                this.mcontent = '当前账户暂无扫码权限'
                return
            }
            // 允许从相机和相册扫码
            uni.scanCode({
                success: function (res) {
                    console.log('条码类型：' + res.scanType);
                    console.log('条码内容：' + res.result);
                    that.loading = true
                    that.$http.get('/app/scan/code/get_goods_by/' + res.result).then(val => {
                        console.log(val.data)
                        let machItem = {
                            machId: val.data.machId,
                            machName: val.data.machName,
                            goods: [],
                            fileList: [],
                        }
                        machItem.type = 0
                        machItem.goods.push(val.data)
                        that.loading = false

                        if (that.recordForm.length == 0) {
                            console.log('第一个')
                            that.recordForm.push(machItem)

                            that[`fileList${that.recordForm.length - 1}`] = []
                        }

                        else {
                            for (var i in that.recordForm) {
                                console.log('循环')
                                if (that.recordForm[i].machId == val.data.machId) {
                                    for (var j in that.recordForm[i].goods) {
                                        if (that.recordForm[i].goods[j].number == val.data.number) {
                                            that.$refs.uNotify.show({
                                                // top: 10,
                                                type: 'error',
                                                color: '#fff',
                                                bgColor: '#FFC386',
                                                message: '请勿重复扫描二维码',
                                                duration: 1000 * 2,
                                                fontSize: 28,
                                                // safeAreaInsetTop: true
                                                safeAreaInsetTop: false
                                            })
                                            return
                                        }
                                        else if (j == that.recordForm[i].goods.length - 1) {
                                            that.recordForm[i].goods.push(val.data)
                                            return
                                        }
                                    }
                                }
                                else if (i == that.recordForm.length - 1) {
                                    that.recordForm.push(machItem)
                                    that[`fileList${that.recordForm.length - 1}`] = []

                                    return
                                }
                            }
                        }
                    }).catch(err => {
                        that.loading = false

                    })
                }
            });
        },
        //弹出日期选择
        hideKeyboard(machIndex) {
            this.nowMachIndex = machIndex
            uni.hideKeyboard()
        },

        birthdayClose() {
            this.showTimePick = false
            this.$refs.form1.validateField('userInfo.birthday')
        },
        birthdayConfirm(e) {
            this.showTimePick = false
            this.recordForm[this.nowMachIndex].constructionTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
            this.$refs.form1.validateField('userInfo.birthday')
        },
        //提交

        submit() {
            let that = this
            console.log(that.recordForm)
            if (this.userInfo.roleName == '商家角色') {
                let paramsdata = {}
                paramsdata.roleId = uni.getStorageSync("userInfo").roleId
                paramsdata.userId = uni.getStorageSync("userInfo").userId
                paramsdata.type = this.recordForm[0].type
                paramsdata.recordsList = []
                for (var j in this.recordForm) {
                    let param = {}
                    param.qrCode = []
                    for (var good in this.recordForm[j].goods) {
                        param.qrCode.push(this.recordForm[j].goods[good].number)
                    }
                    paramsdata.recordsList.push(param)
                }
                console.log(paramsdata)

                uni.showLoading({
                    title: '加载中'
                });
                this.disabledbtn = true
                that.$http.post('app/scan/code/scan_code', paramsdata).then(val => {
                    console.log(val)
                    if (val.data == 1) {

                        that.recordForm = []
                        uni.showToast({
                            title: val.message,
                            icon: "success",
                            duration: 2000
                        });
                        this.disabledbtn = false
                        uni.hideLoading();
                    }
                    else {
                        this.mshow = true
                        this.mcontent = val.message

                        this.disabledbtn = false
                        uni.hideLoading();
                    }
                }).catch(err=>{
                        this.disabledbtn = false
                        uni.hideLoading();
                })

            }
            else {

                let scan_code = true
                for (var i = 0; i < that.recordForm.length; i++) {
                    that.$refs["uForm" + i][0].validate().then(res => {
                        if (i == that.recordForm.length && res) {
                            console.log(this.recordForm)
                            let paramsdata = {}
                            paramsdata.roleId = uni.getStorageSync("userInfo").roleId
                            paramsdata.userId = uni.getStorageSync("userInfo").userId
                            paramsdata.recordsList = []
                            for (var j in this.recordForm) {
                                console.log(this.recordForm[j])
                                let param = {}
                                param.address = this.recordForm[j].address
                                param.constructionTime = this.recordForm[j].constructionTime
                                param.images = this.recordForm[j].images.join(',')
                                param.qrCode = []
                                for (var good in this.recordForm[j].goods) {
                                    param.qrCode.push(this.recordForm[j].goods[good].number)
                                }
                                paramsdata.recordsList.push(param)
                            }
                            if (scan_code == true) {
                                scan_code = false
                                that.$http.post('app/scan/code/scan_code', paramsdata).then(val => {
                                    console.log(val)
                                    if (val.data == 1) {
                                        uni.showToast({
                                            title: val.message,
                                            icon: "success",
                                            duration: 2000
                                        });
                                        that.recordForm = []
                                    }
                                    else {
                                        this.mshow = true
                                        this.mcontent = val.message
                                    }
                                })
                            }
                        }
                    }).catch(errors => {
                        // uni.$u.toast('校验失败')
                    })
                }
            }
        },
    }
}
</script>

<style lang='scss'>
.scanCode {
    min-height: 100vh;
    background-color: #fff;
    padding-bottom: 16vh;
    .u-loading-page {
        .u-loading-icon__spinner {
            width: 50rpx !important;
            height: 50rpx !important;
        }
        .u-loading-page__warpper__text {
            font-size: 30rpx !important;
        }
    }
    .u-transition {
        z-index: 10;
    }
    .u-upload__wrap__preview__image,
    .u-upload__button {
        width: 200rpx !important;
        height: 200rpx !important;
    }
    .u-upload__deletable {
        width: 50rpx !important;
        height: 50rpx !important;
        text {
            top: 20rpx !important;
            font-size: 40rpx !important;
        }
    }
    .u-radio-group {
        margin-top: 20rpx;
        .u-icon__icon {
            font-size: 36rpx;
        }
    }
    .u-form-item__body__right__message {
        margin-left: 0 !important;
    }
    .u-radio__icon-wrap {
        width: 40rpx !important;
        height: 40rpx !important;
    }
    .u-radio__text {
        font-size: 36rpx !important;
        line-height: 36rpx !important;
    }
    .u-radio {
        margin-right: 20rpx;
    }
    .scanCodetopimg {
        position: relative;
        .sandcode {
            width: 100%;
            height: 56vw;
        }
        .grandTotal {
            position: absolute;
            width: 100%;
            height: 150rpx;
            bottom: -80rpx;
        }
        .grandTotalText {
            width: 100%;
            position: absolute;
            padding: 0 10% 0 20%;
            margin: 0 auto;
            height: 150rpx;
            bottom: -85rpx;
            .title {
                font-size: 32rpx;
                font-weight: 600;
                color: #000000;
                line-height: 45rpx;
            }
            .num {
                font-size: 40rpx;
                font-weight: bold;
                color: #ff7300;
                line-height: 30rpx;
            }
        }
    }
    .recordBox {
        padding: 80rpx 40rpx 40rpx 40rpx;
        .recordtitle {
            font-size: 36rpx;
            font-weight: 600;
            color: #333333;
            line-height: 50rpx;
        }
        .recordItem {
            padding: 20rpx 0;
            .dpname {
                font-size: 24rpx;
                font-weight: 400;
                color: #555555;
                line-height: 33rpx;
            }
            .t-table {
                border: 2rpx solid #eaeaea !important;
                border-radius: 10rpx;
                margin-top: 20rpx;
                .t-th {
                    border: 2rpx solid #eaeaea !important;
                    background-color: #fff;
                }
                .tabtitle {
                    .t-th {
                        // border: 2rpx solid #eaeaea !important;

                        font-size: 28rpx;
                        font-weight: 400;
                        color: #555555;
                        line-height: 40rpx;
                    }
                }
                .content {
                    .numbering {
                        text-align: start;
                        font-size: 24rpx;
                        font-weight: 400;
                        color: $themeColor;
                        line-height: 33rpx;
                        background: #f1f6ff;
                        border-radius: 8rpx;
                        padding: 0 10rpx;
                    }
                    .title {
                        text-align: start;
                        font-size: 28rpx;
                        font-weight: 600;
                        color: #555555;
                        line-height: 40rpx;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        line-height: 2;
                    }
                }
                .deleteItem {
                    font-size: 28rpx;

                    color: #1a60ea;
                    font-weight: 400;
                }
            }
            .u-form-item__body {
                display: block;
            }
            .u-form-item__body__left__content__label {
                white-space: nowrap;
                font-size: 36rpx;
                font-weight: 600;
                color: #000000;
                line-height: 50rpx;
                margin-top: 20rpx;
            }
            .u-input {
                margin-top: 20rpx;
                background: #f8f8f8;
                border-radius: 8rpx;
                border: none;
                padding: 20rpx !important;
            }

            .u-picker__view__column,
            .u-picker__view {
                height: 40vh !important;
            }
            .shigongimgs {
                margin-bottom: 40rpx;
                .uicon-camera-fill {
                    font-size: 60rpx !important;
                }
            }
        }
    }
}
</style>